package com.ccx.library.Interceptor;

import cn.hutool.cron.task.Task;
import com.ccx.library.exception.NotTokenException;
import com.ccx.library.handler.Token.TokenFreshenHandler;
import com.ccx.library.response.R;
import com.ccx.library.util.JwtProvide;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
@Order(value = 2147483647)
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenFreshenHandler tokenFreshenHandler;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 访问控制器方法前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }
        String token = request.getHeader("token");
        if (ObjectUtils.isEmpty(JwtProvide.getTokenClaim(token))){
            ObjectMapper objectMapper = new ObjectMapper();
            String notToken = objectMapper.writeValueAsString(R.NotToken());
            response.getWriter().println(notToken);
            return false;
        }
            if (!redisTemplate.hasKey(request.getHeader("AuthKey"))){
                ObjectMapper objectMapper = new ObjectMapper();
                String notToken = objectMapper.writeValueAsString(R.NotToken());
                response.getWriter().println(notToken);
                return false;
            }
            /**
             * token刷新
             */
            if (redisTemplate.hasKey(request.getHeader("AuthKey"))){
                tokenFreshenHandler.fresh(request.getHeader("AuthKey"));
            }
        return true;
    }
    /**
     * 访问控制器方法后执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
